<template>
    <div class="white-box">
        <cell-tip show-more :datas="tipArrs" />
        <applet-tip-auth v-if="supplier_auth_applet == 0" @click="clickAuth(1)" />
        <div v-loading="loading" element-loading-text="请求中，耐心等待..." v-else>
            <title-more title="版本信息" bgcolor style="margin: 14px 0px 6px" />
            <div class="info-item">
                <div class="info-item__left">线上版本：</div>
                <div class="info-item__right flexs">
                    <div class="right-text">{{ userAppletObj.release_info ? userAppletObj.release_info.release_version : "--" }}</div>
                    <div class="right-nav">
                        <el-popover placement="left" :width="200" trigger="click" v-if="tycode">
                            <template #reference>
                                <span>查看体验版</span>
                            </template>
                            <img :src="proxy.imgUrl + tycode" alt="小程序体验码" />
                        </el-popover>
                        <span @click.stop="clickBack">版本回退</span>
                        <span @click.stop="clickUpdate">更新记录</span>
                    </div>
                </div>
            </div>
            <div class="info-item">
                <div class="info-item__left">更新时间：</div>
                <div class="info-item__right flexs">
                    <div class="right-text">
                        <span v-if="userAppletObj.created_time">于 {{ userAppletObj.created_time }} 更新</span><span v-else>--</span>
                    </div>
                    <div class="right-nav"></div>
                </div>
            </div>
            <div class="info-item">
                <div class="info-item__left">审核状态：</div>
                <div class="info-item__right flexs">
                    <div class="right-text">
                        <p
                            class="link-item"
                            style="color: #ff4d50; cursor: pointer"
                            @click.stop="viewReason(userExamObj)"
                            v-if="userExamObj.status == 1"
                        >
                            {{ userExamObj.status_label }}<el-icon color="#FF4D50" size="18px"><WarningFilled /></el-icon>
                        </p>
                        <template v-if="userExamObj.status != 1">
                            <span
                                :style="{ color: userExamObj.status == 0 ? '#1AAD19' : '#4B93FA' }"
                                v-if="userExamObj.status_label"
                            >
                                {{ userExamObj.status_label }}
                            </span>
                            <span v-else>--</span>
                        </template>
                    </div>
                    <div class="right-nav" style="flex: 1; text-align: right">
                        <!-- <span @click.stop="clickWithdraw" v-if="userExamObj.status == 2">撤回审核</span> -->
                        <span @click.stop="clickUploadCode" v-if="userExamObj.status != 2">提交代码</span>
                        <span @click.stop="clickExamine" v-if="userExamObj.status != 2">提交审核</span>
                        <!-- v-if="userExamObj.status == 0 && userExamObj.type == 2" -->
                        <el-tooltip class="box-item" effect="dark" content="请审核成功后再点击发布" placement="top-start">
                            <span @click.stop="clickRelease" v-if="userExamObj.status == 0">发布</span>
                        </el-tooltip>
                    </div>
                </div>
            </div>
            <title-more title="基本信息" bgcolor style="margin: 30px 0px 10px">
                <template #right>
                    <p style="color: #4b93fa;cursor: pointer;" @click="toUpdate">更新信息</p>
                </template>
            </title-more>
            <div class="info-item">
                <div class="info-item__left">小程序名称：</div>
                <div class="info-item__right flexs">
                    <div class="right-text">{{ userObjs.nick_name }}</div>
                    <div class="right-nav"></div>
                </div>
            </div>
            <div class="info-item">
                <div class="info-item__left">小程序头像：</div>
                <div class="info-item__right flexs">
                    <div class="right-text">
                        <el-avatar :size="50" :src="userObjs.head_img" />
                    </div>
                    <div class="right-nav"></div>
                </div>
            </div>
            <div class="info-item">
                <div class="info-item__left">服务类目：</div>
                <div class="info-item__right flexs">
                    <div class="right-text">
                        <span v-if="userObjs.first_class">{{ userObjs.first_class }} > {{ userObjs.second_class }}</span>
                        <span v-else>暂无类目</span>
                    </div>
                    <div class="right-nav"></div>
                </div>
            </div>
            <div class="info-item">
                <div class="info-item__left">主体信息：</div>
                <div class="info-item__right flexs">
                    <div class="right-text">{{ userObjs.principal_name }}</div>
                    <div class="right-nav"></div>
                </div>
            </div>
            <div class="info-item">
                <div class="info-item__left">AppID(小程序ID)：</div>
                <div class="info-item__right flexs">
                    <div class="right-text">{{ userObjs.authorizer_appid }}</div>
                    <div class="right-nav"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- 更新记录 -->
    <el-dialog class="dialog-pages" v-model="dialogRecord" title="更新记录" top="11vh" width="740px" :append-to-body="true" :destroy-on-close="true">
        <el-table
            class="table-mb"
            :data="recordArrs"
            :header-cell-style="{ background: '#F5F7FA' }"
            element-loading-background="rgba(255, 255, 255, 0.6)"
            v-loading="recordLoading"
        >
            <el-table-column prop="user_version" label="审核版本"></el-table-column>
            <el-table-column prop="user_desc" label="版本描述"></el-table-column>
            <el-table-column label="提交类型">
                <template #default="{ row }">
                    <span style="color: #4b93fa">{{ row.type == 1 ? "提交代码" : "提交审核" }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="updated_at_label" label="提交时间" width="160"></el-table-column>
            <el-table-column label="状态" width="140" class-name="operation-nav" fixed="right">
                <template #default="{ row }">
                    <p class="link-item" style="color: #ff4d50; cursor: pointer" @click.stop="viewReason(row)" v-if="row.status == 1">
                        {{ row.status_label }}<el-icon color="#FF4D50" size="18px"><WarningFilled /></el-icon>
                    </p>
                    <p class="link-item" :style="{ color: row.status == 0 ? '#1AAD19' : '#4B93FA' }" v-else>
                        {{ row.status_label }}
                    </p>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination background v-model:current-page="recordPage" :page-size="10" :total="totalRecord" layout="total, prev, pager, next, jumper">
        </el-pagination>
    </el-dialog>

    <!-- 回退版本列表 -->
    <el-drawer
        title="回退版本列表"
        v-model="dialogEdition"
        direction="rtl"
        size="500px"
        :append-to-body="true"
        :destroy-on-close="true"
        @close="dialogEdition = false"
    >
        <el-table
            class="table-mb"
            :data="editionArrs"
            :header-cell-style="{ background: '#F5F7FA' }"
            element-loading-background="rgba(255, 255, 255, 0.6)"
            v-loading="editionLoading"
        >
            <el-table-column prop="user_version" label="小程序版本"></el-table-column>
            <el-table-column prop="created_time" label="更新时间"></el-table-column>
            <el-table-column label="操作" width="140" class-name="operation-nav" fixed="right">
                <template #default="{ row }">
                    <p class="link-item" style="color: #4b93fa" @click.stop="confirmBack(row)">回退此版本</p>
                </template>
            </el-table-column>
        </el-table>
        <!-- <el-pagination background v-model:current-page="editionPage" :page-size="10" :total="totalEdition" layout="total, prev, pager, next, jumper">
        </el-pagination> -->
    </el-drawer>

    <!-- 提交审核前准备 -->
    <el-dialog class="dialog-pages" v-model="dialogExam" title="提交审核" width="720px" :append-to-body="true" :destroy-on-close="true">
        <cell-tip tip="请确认您是否已进行“提交代码”操作，在下方输入测试账号和密码用于审核使用" />
        <div class="exam-form">
            <el-form ref="ruleRefExam" :model="ruleFormExam" :rules="ruleCheckExam" label-width="140px">
                <el-form-item label="测试账号" prop="tel">
                    <el-input
                        v-model.trim="ruleFormExam.tel"
                        maxlength="11"
                        oninput="value=value.replace(/[^\d]/g,'')"
                        placeholder="测试账号（手机号码）"
                        clearable
                    />
                </el-form-item>
                <el-form-item label="测试密码" prop="pass">
                    <el-input v-model.trim="ruleFormExam.pass" placeholder="测试密码" clearable show-password> </el-input>
                </el-form-item>
                <el-form-item>
                    <div class="flexs" style="margin-top: 20px">
                        <el-button type="primary" :loading="form_loading" @click="submitFormExam(ruleRefExam)">确认提交</el-button>
                        <el-button @click="resetFormExam(ruleRefExam)">重置</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </div>
    </el-dialog>

    <!-- 审核失败原因 -->
    <el-dialog
        class="dialog-pages"
        v-model="dialogReason"
        title="审核失败原因"
        width="620px"
        top="18vh"
        :append-to-body="true"
        :destroy-on-close="true"
    >
        <div>
            <detail-item title="失败原因" bottom="20px" title-width="70px" value-color="#000" v-if="recordObj.commit">
                <div v-html="recordObj.commit.reason || '无'"></div>
            </detail-item>
            <detail-item title="失败原因" bottom="20px" title-width="70px" value-color="#000" v-else>
                <div v-html="recordObj.reason || '无'"></div>
            </detail-item>
        </div>
    </el-dialog>
</template>

<script setup>
import { getCurrentInstance, ref, computed, onMounted, watch, reactive } from "vue"
import { useBaseStore } from "@store/base"
import { WarningFilled } from "@element-plus/icons-vue"
import TitleMore from "@components/title-more.vue"
import AppletTipAuth from "@components/AppletTipAuth.vue"
import CellTip from "@components/cell-tip.vue"
import DetailItem from "@components/DetailItem.vue"

const { proxy } = getCurrentInstance()

// 用户端小程序是否已经授权，0否，1是
const storeBase = useBaseStore()
const supplier_auth_applet = computed(() => {
    return storeBase.supplier_auth_applet // 用户端小程序是否已经授权，0否，1是
})
// 提示文本
const tipArrs = [
    "注意",
    "提交步骤：请先提交代码，然后再提交审核，待审核通过后点击“发布”按钮进行发布，最后点击发布即可上线小程序。",
    "更新记录：查看之前提交的版本信息",
    "回退版本：除非最新的线上版本有问题时，可选择回退版本，否则建议不要回退版本（可能会影响小程序部分功能）",
    "更新信息：点击更新信息后会获取最新的小程序信息",
    "提交代码成功后会生成体验版，此时可点击查看体验版进行扫码体验（建议首次查看体验版请先提交审核及发布小程序）",
]
const loading = ref(false)

onMounted(() => {
    getAuthInfo()
})

// 更新小程序信息
const toUpdate = () => {
    loading.value = true
    proxy.$axios
        .post("mp/authInfoUpdate", {
            client_os:'supplier_mini_program'
        })
        .then((res) => {
            if (res.data.code == 0) {
                proxy.$message({ message: '更新成功！', type: "success" })
                getAuthInfo()
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

// 获取授权小程序信息
const userObjs = ref({})
function getAuthInfo(status = true) {
    proxy.$axios
        .get("mp/authInfo", {
            params: {
                client_os: "supplier_mini_program",
            },
        })
        .then((res) => {
            loading.value = false
            if (res.data.code == 0) {
                userObjs.value = res.data.data
                if (status) {
                    getAppletInfo()
                    getExamStatus()
                }
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {
            loading.value = false
        })
}

// 查询小程序版本信息
const userAppletObj = ref({})
function getAppletInfo() {
    proxy.$axios
        .get("mp/getVersionInfo", {
            params: {
                client_os: "supplier_mini_program",
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                if (result.release_info && Object.keys(result.release_info).length > 0) {
                    result.created_time = proxy.$util.formatDate(result.release_info.release_time)
                }
                userAppletObj.value = result
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}

// 查询最新模板库及最新提交记录
const userExamObj = ref({})
function getExamStatus() {
    proxy.$axios
        .get("mp/versionTemplate", {
            params: {
                client_os: "supplier_mini_program",
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                let statusArrs = ["审核成功", "审核被拒绝", "审核中", "已撤回", "审核延后", "已发布"]
                let statusArrsTwo = ["上传代码成功，等待提交审核", "代码未通过", "代码审核中", "已撤回代码", "代码审核延后"]
                if (result.commit) {
                    result.status = result.commit.status
                    result.type = result.commit.type
                    if (result.commit.type == 1) {
                        // 提交代码状态格式化
                        result.status_label = statusArrsTwo[result.commit.status] || ""
                    } else {
                        result.status_label = statusArrs[result.commit.status] || ""
                    }
                    getTyCode()
                }
                result.commit_status = result.commit.template_id === result.template.template_id
                userExamObj.value = result
                // console.log("审核状态", result)
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}
// 获取体验码
const tycode = ref("")
function getTyCode() {
    proxy.$axios
        .get("mp/getTrialQRCode", {
            params: {
                client_os: "supplier_mini_program",
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                tycode.value = result.path
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}

// 上传代码审核
const clickUploadCode = () => {
    loading.value = true
    proxy.$axios
        .post("mp/commit", {
            client_os: "supplier_mini_program",
        })
        .then((res) => {
            loading.value = false
            if (res.data.code == 0) {
                proxy.$message({ message: "代码已上传成功，请点击提交代码审核！", type: "success" })
                getAuthInfo()
                if (userObjs.value.set_privacy == 0) {
                    userPrivacy()
                }
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {
            loading.value = false
        })
}
// 设置用户保护隐私指引
function userPrivacy() {
    proxy.$axios
        .post("mp/setPrivacySetting", {
            client_os: "supplier_mini_program",
        })
        .then((res) => {
            if (res.data.code != 0) {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}

/**
 * 提交审核
 * @param {Boolean} dialogAgentOne 弹窗状态
 * @param {Object} ruleRefExam 表单规则
 * @param {Object} ruleFormExam  表单字段
 * @param {Array} ruleCheckExam  表单提示
 */
const dialogExam = ref(false)
const form_loading = ref(false)
const ruleRefExam = ref(null)
const ruleFormExam = reactive({
    tel: "",
    pass: "",
})
const ruleCheckExam = reactive({
    tel: [{ required: true, validator: proxy.$util.validPhone, trigger: "blur" }],
    pass: [{ required: true, message: "请输入密码", trigger: "blur" }],
})
const submitFormExam = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            form_loading.value = true
            proxy.$axios
                .post("mp/submitAudit", {
                    client_os: "supplier_mini_program",
                    account_name: ruleFormExam.tel,
                    account_password: ruleFormExam.pass,
                })
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        dialogExam.value = false
                        proxy.$message({ message: "提交成功，等待小程序审核！", type: "success" })
                        getAuthInfo()
                    } else {
                        proxy.$message({message:res.data.msg,type:"error"})
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetFormExam = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
const clickExamine = () => {
    dialogExam.value = true
}

// 发布代码
const clickRelease = () => {
    loading.value = true
    proxy.$axios
        .post("mp/release", {
            client_os: "supplier_mini_program",
        })
        .then((res) => {
            loading.value = false
            if (res.data.code == 0) {
                proxy.$message({ message: "发布成功！", type: "success" })
                getAuthInfo()
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {
            loading.value = false
        })
}

// 撤回审核-暂时隐藏
const clickWithdraw = () => {
    proxy.$confirm("请确认要撤回代码审核吗？", "温馨提示", {
        type: "warning",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
    })
        .then(() => {
            proxy.$axios
                .post("mp/undoAudit", {
                    client_os: 'supplier_mini_program',
                })
                .then((res) => {
                    if (res.data.code == 0) {
                        proxy.$message({ message: "撤回代码审核成功！", type: "success" })
                        getAuthInfo()
                    } else {
                        proxy.$message({message:res.data.msg,type:"error"})
                    }
                })
                .catch((err) => {})
        })
        .catch(() => {})
}

/**
 * 更新记录
 * @param {Boolean} recordLoading 弹窗加载状态
 * @param {Boolean} dialogRecord 弹窗状态
 * @param {Boolean} recordArrs 数组
 * @param {Function} getRecord
 */
const recordLoading = ref(false)
const dialogRecord = ref(false)
const recordPage = ref(1)
const totalRecord = ref(0)
const recordArrs = ref([])
const clickUpdate = () => {
    dialogRecord.value = true
    recordArrs.value = []
    getRecord()
}
watch(recordPage, (val) => {
    recordArrs.value = []
    getRecord()
})
function getRecord() {
    recordLoading.value = true
    proxy.$axios
        .get("mp/versionCommit", {
            params: {
                client_os: "supplier_mini_program",
                page: recordPage.value,
                limit: 10,
            },
        })
        .then((res) => {
            recordLoading.value = false
            if (res.data.code == 0) {
                let result = res.data.data
                let statusArrs = ["审核成功", "审核被拒绝", "审核中", "已撤回", "审核延后", "已发布"]
                let statusArrsTwo = ["上传代码成功，等待提交审核", "代码未通过", "代码审核中", "已撤回代码", "代码审核延后"]
                result.map((item) => {
                    if (item.type == 1) {
                        item.status_label = statusArrsTwo[item.status]
                    } else {
                        item.status_label = statusArrs[item.status]
                    }
                })
                totalRecord.value = res.data.count
                recordArrs.value = result
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {
            recordLoading.value = false
        })
}

/**
 * 回退版本
 * @param {Boolean} editionLoading 弹窗加载状态
 * @param {Boolean} dialogEdition 弹窗状态
 * @param {Boolean} recordArrs 数组
 * @param {Function} getEdition
 */
const editionLoading = ref(false)
const dialogEdition = ref(false)
// const editionPage = ref(1)
// const totalEdition = ref(0)
const editionArrs = ref([])
const clickBack = () => {
    dialogEdition.value = true
    getEdition()
}
// 确认回退版本
const confirmBack = (row) => {
    proxy.$confirm("回退版本可能会造成小程序部分功能缺失，请确认回退版本吗？", "温馨提示", {
        type: "warning",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
    })
        .then(() => {
            proxy.$axios
                .post("mp/revertCodeRelease", {
                    client_os: "supplier_mini_program",
                    app_version: row.app_version,
                })
                .then((res) => {
                    if (res.data.code == 0) {
                        dialogEdition.value = false
                        getAuthInfo()
                    } else {
                        proxy.$message({message:res.data.msg,type:"error"})
                    }
                })
                .catch((err) => {
                    editionLoading.value = false
                })
        })
        .catch(() => {})
}
// watch(editionPage, (val) => {
//     editionArrs.value = []
//     getEdition()
// })
function getEdition() {
    editionLoading.value = true
    proxy.$axios
        .post("mp/getHistoryVersion", {
            client_os: "supplier_mini_program",
            // page: editionPage.value,
            // limit: 10,
        })
        .then((res) => {
            editionLoading.value = false
            if (res.data.code == 0) {
                let result = res.data.data
                // totalEdition.value = res.data.count
                result.version_list.map((item) => {
                    item.created_time = proxy.$util.formatDate(item.commit_time)
                })
                editionArrs.value = result.version_list
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {
            editionLoading.value = false
        })
}

/**
 * 查看审核失败原因
 * @param {Boolean} dialogReason 弹窗
 */
const recordObj = ref({})
const dialogReason = ref(false)
const viewReason = (row) => {
    recordObj.value = row
    dialogReason.value = true
}
</script>
<script>
export default {
    name: "AppletManageSupp",
}
</script>

<style lang="less" scoped>
.exam-form {
    margin-top: 40px;
}
.link-item {
    display: flex;
    align-items: center;
    .el-icon {
        margin-left: @margin-base;
    }
}
.info-item {
    display: flex;
    height: 76px;
    align-items: center;
    .info-item__left {
        flex: none;
        width: 140px;
        text-align: right;
        font-size: @font-size-md;
        color: @gray-7;
        margin-right: @margin-sm;
    }
    .info-item__right {
        flex: 1;
        border-bottom: 1px solid @gray-3;
        height: 100%;
        padding-top: @padding-base;
        .right-text {
            flex: 1;
            color: #111;
            font-size: @font-size-md;
        }
        .right-nav {
            flex: none;
            span {
                font-size: @font-size-md;
                color: @themes;
                margin-left: @margin-lg;
                cursor: pointer;
            }
        }
    }
}
</style>
<style lang="less">
.dialog-pages {
    .el-dialog__body {
        padding: 10px 20px 20px;
    }
}
</style>
